import React,{useEffect, useState} from 'react';
import { Modal, Form, Input, Checkbox, Row, Col, message } from 'antd';
import { FormInstance } from 'antd/lib/form';
import { DeviceAuthListItem } from '../data.d';
import { deviceDictList } from '../service';

interface AddDeviceAuthFormProps {
  modalVisible: boolean;
  onCancel: () => void;
  onSubmit: (values: DeviceAuthListItem) => void;
  values: DeviceAuthListItem;
}

const layout = {
  labelCol: { span: 4 },
  wrapperCol: { span: 16 },
};

const formRef = React.createRef<FormInstance>();

const AddDeviceAuthForm: React.FC<AddDeviceAuthFormProps> = (props) => {
  const { modalVisible, onSubmit, onCancel, values } = props;
  const [form] = Form.useForm();
  const [commandList, setCommandList] = useState([]);

  const handleFinish = (values: { [key: string]: any }) => {
    if (onSubmit) {
      onSubmit(values as DeviceAuthListItem);
    }
  };

  const handleUpdate = () => {
    if (!form) return;
    form.submit();
  };

  const modalFooter = { okText: '保存', onOk: handleUpdate, onCancel };

  useEffect(() => {
    if(modalVisible){
      new Promise((resolve, reject) => {
        deviceDictList()
          .then((res) => {
            if (res.code === 200) {
              setCommandList(res.data);
              form.setFieldsValue({commands:(values.commands)?.split(",")});
              resolve(true);
            } else {
              message.error('功能列表请求失败，'+res.message);
              resolve(false);
            }
          })
          .catch((error) => {
            message.error('添加失败');
            reject(error);
          });
      });
      if(values.id){//编辑
        form.setFieldsValue({
          id:values.id,
          deviceVersion: values.deviceVersion,
          boardModel: values.boardModel,
          description: values.description,
        });
      }else{//新建
        form.resetFields();
      }
    }
  },[modalVisible]);

  const onChange = (checkedValues:any) => {
    console.log('checked = ', checkedValues);
  }

  const renderContent = () => {
    return (
      <>
        <Form.Item name="id" style={{ display: 'none' }}></Form.Item>
        <Form.Item
          name="deviceVersion"
          label="固件版本"
          rules={[
            { required: true, whitespace: true}]}
        >
          <Input placeholder="请输入固件版本" /> 
        </Form.Item>
        <Form.Item
          name="boardModel"
          label="板卡型号"
          rules={[
            { required: true, whitespace: true}]}
        >
          <Input placeholder="请输入板卡型号" />
        </Form.Item>
        <Form.Item name="commands" label="开通功能" rules={[{ required: true }]}>
          <Checkbox.Group style={{ width: '100%' }} onChange={onChange}>
            <Row>
              {commandList.map((item,index)=>{
                return (
                <Col span={8}>
                  <Checkbox value={item.dataCode}>{item.dataValue}</Checkbox>
                </Col>)
              })}
            </Row>
          </Checkbox.Group>
        </Form.Item>
        <Form.Item name="description" label="描述" >
            <Input.TextArea rows={4} style={{resize:"none"}}/>
        </Form.Item>
      </>
    );
  };
  return (
    <Modal 
      destroyOnClose 
      title={(values && values.id)?"编辑设备类型":"添加设备类型"} 
      visible={modalVisible} 
      {...modalFooter} 
      centered
      >
      <Form 
        {...layout} 
        ref={formRef} 
        form={form}
        onFinish={handleFinish}>
        {renderContent()}
      </Form>
    </Modal>
  );
};

export default AddDeviceAuthForm;
